package com.example.tool

import android.app.AppOpsManager
import android.app.usage.UsageStatsManager
import android.content.Context
import android.content.Intent
import android.content.pm.ApplicationInfo
import android.content.pm.PackageManager
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.view.View
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.animation.core.spring
import androidx.compose.animation.core.animateFloatAsState
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import com.example.tool.ui.theme.ToolTheme
import java.util.Calendar
import androidx.compose.material3.MaterialTheme.colorScheme
import androidx.compose.ui.graphics.drawscope.drawIntoCanvas
import androidx.compose.ui.graphics.drawscope.translate
import androidx.compose.ui.graphics.drawscope.withTransform
import androidx.compose.ui.graphics.nativeCanvas
import androidx.compose.ui.graphics.toArgb
import androidx.compose.ui.graphics.withSave
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.text.TextPainter
import androidx.compose.ui.text.drawText
import androidx.compose.ui.text.rememberTextMeasurer
import androidx.compose.ui.unit.sp
import kotlin.time.Duration.Companion.hours
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import kotlin.math.abs
import kotlin.math.atan2
import kotlin.math.cos
import kotlin.math.sin


class MainActivity : ComponentActivity() {
    private val logMessages = mutableStateListOf<String>()
    private val logFileName = "app_usage_log.txt"
    private lateinit var installedApps: List<ApplicationInfo>
    private var selectedDays by mutableStateOf(7)
    private var selectedAppCount by mutableStateOf(10)
    private var appUsagesState = mutableStateOf<List<MainActivity.AppUsage>>(emptyList())

    //    private fun writeToLogFile(message: String) {
//        try {
//            val logFile = File(getExternalFilesDir(null), logFileName)
//            logFile.appendText("${SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(Date())}: $message\n")
//        } catch (e: Exception) {
//            Log.e("FileLog", "Error writing to log file", e)
//        }
//    }
    private var showPermissionDialog by mutableStateOf(false)
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        // 随机选择一个背景图片
//        val backgroundResources = listOf(
//            R.drawable.dm4,
//            R.drawable.dm2,
//            R.drawable.dm
//        )
//        val randomBackground = backgroundResources.random()
//
//        // 设置窗口背景
//        window.setBackgroundDrawableResource(randomBackground)

        if (!checkUsageStatsPermission()) {
            showPermissionDialog = true
        }

        // 初始化 installedApps 列表
        installedApps = packageManager.getInstalledApplications(PackageManager.GET_META_DATA)

        setContent {
            ToolTheme {
                Surface(
                    modifier = Modifier.fillMaxSize(),
                    color = MaterialTheme.colorScheme.background
                ) {
                    if (showPermissionDialog) {
                        PermissionRequiredDialog {
                            startActivity(Intent(Settings.ACTION_USAGE_ACCESS_SETTINGS))
                            showPermissionDialog = false
                        }
                    } else {
                        ChartScreen(
                            appUsages = appUsagesState.value,
                            logMessages = logMessages,
                            selectedDays = selectedDays,
                            selectedAppCount = selectedAppCount,
                            onDaysSelected = { days ->
                                selectedDays = days
                                loadAppUsageData() },
                            onCountSelected = { count ->
                                selectedAppCount = count
                                loadAppUsageData() }
                        )
                    }
                }
            }
        }
    }

    private fun checkUsageStatsPermission(): Boolean {
        val appOps = getSystemService(Context.APP_OPS_SERVICE) as AppOpsManager
        val mode = appOps.checkOpNoThrow(
            AppOpsManager.OPSTR_GET_USAGE_STATS,
            android.os.Process.myUid(),
            packageName
        )
        return mode == AppOpsManager.MODE_ALLOWED
    }

    @Composable
    fun PermissionRequiredDialog(onDismiss: () -> Unit) {
        AlertDialog(
            onDismissRequest = onDismiss,
            title = { Text("需要使用统计权限") },
            text = { Text("请开启使用统计权限以查看应用使用时长") },
            confirmButton = {
                TextButton(onClick = onDismiss) {
                    Text("去设置")
                }
            }
        )
    }

    override fun onResume() {
        super.onResume()
        if (checkUsageStatsPermission()) {
            showPermissionDialog = false
            loadAppUsageData()
        }
    }

    private fun loadAppUsageData() {
        // 重新加载应用使用数据
        val appUsages = fetchAppUsageStats(selectedDays).take(selectedAppCount)
        // 更新界面
        appUsagesState.value = appUsages
    }

    private fun fetchAppUsageStats(days: Int): List<AppUsage> {
        val usageStatsManager = getSystemService(Context.USAGE_STATS_SERVICE) as UsageStatsManager
        val calendar = Calendar.getInstance().apply {
            add(Calendar.DATE, -days + 1) // 根据选择的天数动态调整
            set(Calendar.HOUR_OF_DAY, 0)
            set(Calendar.MINUTE, 0)
            set(Calendar.SECOND, 0)
            set(Calendar.MILLISECOND, 0)
        }
        val startTime = calendar.timeInMillis
        val endTime = System.currentTimeMillis()

        if (startTime >= endTime) return emptyList()

        // 使用最佳间隔获取精确数据
        val stats = usageStatsManager.queryUsageStats(
            UsageStatsManager.INTERVAL_BEST,
            startTime,
            endTime
        ) ?: return emptyList()

        val appMap = mutableMapOf<String, Long>().apply {
            stats.asSequence()
                .filter { it.totalTimeInForeground > 0 }
                .forEach { usage ->
                    val appName = getAppName(this@MainActivity, usage.packageName).takeIf {
                        it !in listOf("系统应用", "未知应用")
                    } ?: return@forEach

                    // 合并相同应用的不同时间段数据
                    merge(appName, usage.totalTimeInForeground) { old, new ->
                        (old + new).coerceAtMost(24.hours.inWholeMilliseconds * 7) // 限制最大为7天总时间
                    }
                }
        }

        return appMap.asSequence()
            .map { (name, ms) ->
                val hours = (ms.toFloat() / 3600000f).coerceIn(0f, 24f * 7) // 有效范围限制
                AppUsage(
                    appName = name,
                    hours = hours,
                    index = abs(name.hashCode()) // 使用名称哈希保证颜色一致性
                )
            }
            .filter { it.hours > 0.1f } // 过滤小于6分钟的使用记录
            .sortedByDescending { it.hours }
            .toList()
    }

    private fun getAppName(context: Context, packageName: String): String {
        val packageManager = context.packageManager
        for (appInfo in installedApps) {
            if (appInfo.packageName == packageName) {
                val isSystemApp =
                    (appInfo.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0
                if (isSystemApp) {
                    Log.d("AppInfo", "系统应用包名: $packageName")
                    return "系统应用"
                } else {
                    val appName = packageManager.getApplicationLabel(appInfo).toString()
                    val logMessage = "Package: ${packageName}, App Name: $appName"
                    Log.d("AppUsageStats", logMessage)
                    logMessages.add("${SimpleDateFormat("HH:mm:ss").format(Date())} - $logMessage")
                    return appName
                }
            }
        }
        // 检查是否是系统应用
        return try {
            val appInfo = packageManager.getApplicationInfo(packageName, 0)
            val isSystemApp =
                (appInfo.flags and (ApplicationInfo.FLAG_SYSTEM or ApplicationInfo.FLAG_UPDATED_SYSTEM_APP)) != 0
            if (isSystemApp) {
                Log.d("AppInfo", "系统应用包名: $packageName")
                return "系统应用"
            }
            // 获取应用名称
            packageManager.getApplicationLabel(appInfo).toString()
        } catch (e: PackageManager.NameNotFoundException) {
            Log.e("AppName", "Package not found: $packageName", e)
            "未知应用"
        } catch (e: Exception) {
            Log.e("AppName", "Error getting app name for package: $packageName", e)
            "错误：${e.localizedMessage}"
        }
    }

    // 其他 Composable 函数...
    // 例如: ChartScreen, TreeBarChart 等...
    data class AppUsage(
        val appName: String,
        val hours: Float,
        val index: Int
    ) {
        val color: Color by lazy {
            com.example.tool.ui.theme.generateDistinctColor(index = index)
        }
    }
    // ...继续其他 Composable 函数定义，如 ChartScreen 和 TreeBarChart
}

@Composable
private fun ChartScreen(
    appUsages: List<MainActivity.AppUsage>,
    logMessages: List<String> = emptyList(),
    selectedDays: Int,
    selectedAppCount: Int,
    onDaysSelected: (Int) -> Unit,
    onCountSelected: (Int) -> Unit
) {
    val daysOptions = listOf(2, 3, 5, 7)
    val countOptions = listOf(5, 10, 15)

    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(16.dp),
        horizontalAlignment = Alignment.CenterHorizontally
    ) {
        // 时间选择和应用数量选择
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            var showDaysDropdown by remember { mutableStateOf(false) }
            Box {
                TextButton(onClick = { showDaysDropdown = true }) {
                    Text("过去${selectedDays}天 ▼")
                }
                DropdownMenu(
                    expanded = showDaysDropdown,
                    onDismissRequest = { showDaysDropdown = false }
                ) {
                    daysOptions.forEach { days ->
                        DropdownMenuItem(
                            text = { Text("过去${days}天") },
                            onClick = {
                                onDaysSelected(days)
                                showDaysDropdown = false
                            }
                        )
                    }
                }
            }

            var showCountDropdown by remember { mutableStateOf(false) }
            Box {
                TextButton(onClick = { showCountDropdown = true }) {
                    Text("显示${selectedAppCount}个应用 ▼")
                }
                DropdownMenu(
                    expanded = showCountDropdown,
                    onDismissRequest = { showCountDropdown = false }
                ) {
                    countOptions.forEach { count ->
                        DropdownMenuItem(
                            text = { Text("显示${count}个") },
                            onClick = {
                                onCountSelected(count)
                                showCountDropdown = false
                            }
                        )
                    }
                }
            }
        }

        // 顶部时间显示
        Text(
            text = "使用总时长：%.1f小时".format(appUsages.sumOf { it.hours.toDouble() }),
            style = MaterialTheme.typography.headlineLarge.copy(
                fontWeight = FontWeight.ExtraBold
            ),
            color = colorScheme.primary,
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 24.dp)
                .wrapContentWidth(Alignment.CenterHorizontally)
        )

        // 柱状图区域
        Box(
            modifier = Modifier
                .weight(0.6f)
                .fillMaxWidth()
                .background(
                    color = colorScheme.surfaceVariant.copy(alpha = 0.1f),
                    shape = MaterialTheme.shapes.extraLarge
                )
                .padding(24.dp)
                .border(
                    width = 1.dp,
                    color = colorScheme.outline.copy(alpha = 0.3f),
                    shape = MaterialTheme.shapes.extraLarge
                )
        ) {
            TreeBarChart(appUsages = appUsages)
        }

        // 饼状图区域
        Box(
            modifier = Modifier
                .weight(0.4f)
                .fillMaxWidth()
                .background(
                    color = colorScheme.surfaceVariant.copy(alpha = 0.1f),
                    shape = MaterialTheme.shapes.extraLarge
                )
                .padding(24.dp)
                .border(
                    width = 1.dp,
                    color = colorScheme.outline.copy(alpha = 0.3f),
                    shape = MaterialTheme.shapes.extraLarge
                )
        ) {
            PieChart(appUsages = appUsages)
        }
    }
}

@Composable
private fun PieChart(
    appUsages: List<MainActivity.AppUsage>
) {
    val totalHours = appUsages.sumOf { it.hours.toDouble() }.toFloat()
    val textMeasurer = rememberTextMeasurer()
    var selectedIndex by remember { mutableIntStateOf(-1) }
    val density = LocalDensity.current
    val angles = remember { mutableStateListOf<Pair<Float, Float>>() } // 使用 mutableStateListOf
    val scale by animateFloatAsState(
        targetValue = if (selectedIndex != -1) 1.1f else 1f,
        animationSpec = spring(dampingRatio = 0.5f)
    )

    // 每次 appUsages 更新时重新计算角度
    LaunchedEffect(appUsages) {
        selectedIndex = -1
//        angles.clear()
//        var currentStart = 0f
//        appUsages.forEach { usage ->
//            val sweep = (usage.hours / totalHours) * 360f
//            angles.add(currentStart to sweep)
//            currentStart += sweep
//        }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        val floatAmount = with(density) { 10.dp.toPx() }
        Canvas(
            modifier = Modifier
                .fillMaxSize()
                .pointerInput(appUsages) {
                    detectTapGestures { offset ->
                        val center = Offset((size.width / 2).toFloat(), (size.height / 2).toFloat())
                        val clickAngle = Math.toDegrees(
                            atan2(
                                offset.y - center.y,
                                offset.x - center.x
                            ).toDouble()
                        ).toFloat().let {
                            if (it < 0) it + 360 else it
                        }
                        println("ClickAngle: $clickAngle")

                        // 每次点击时重新计算 angles
                        angles.clear()
                        var currentStart = 0f
                        appUsages.forEachIndexed { index, usage ->
                            val sweep = (usage.hours / totalHours) * 360f
                            angles.add(currentStart to sweep)
                            currentStart += sweep
                            // 打印日志
                            Log.d(
                                "PieChart",
                                "Fan Zone $index: Start Angle = ${currentStart - sweep}, Sweep = $sweep"
                            )
                        }

                        angles.forEachIndexed { index, (start, sweep) ->
                            if (clickAngle in start..(start + sweep)) {
                                selectedIndex = index
                                return@detectTapGestures
                            }
                        }
                        selectedIndex = -1
                    }
                }
        ) {
            val radius = (size.minDimension / 2 * 0.8f).coerceAtLeast(10f)
            val center = Offset(size.width / 2, size.height / 2)

            withTransform({
                scale(scale, scale, center)
            }) {
                var startAngle = 0f
                appUsages.forEachIndexed { index, usage ->
                    val sweepAngle = (usage.hours / totalHours) * 360f
                    val color = usage.color
                    if (index == selectedIndex) {
                        val angleRadians = Math.toRadians((startAngle + sweepAngle / 2).toDouble())
                        val offsetX = cos(angleRadians) * floatAmount
                        val offsetY = sin(angleRadians) * floatAmount
                        translate(left = offsetX.toFloat(), top = offsetY.toFloat()) {
                            drawArc(
                                color = color.copy(alpha = 0.8f),
                                startAngle = startAngle,
                                sweepAngle = sweepAngle,
                                useCenter = true,
                                topLeft = Offset(center.x - radius, center.y - radius),
                                size = Size(radius * 2, radius * 2)
                            )
                        }
                    } else {
                        drawArc(
                            color = color,
                            startAngle = startAngle,
                            sweepAngle = sweepAngle,
                            useCenter = true,
                            topLeft = Offset(center.x - radius, center.y - radius),
                            size = Size(radius * 2, radius * 2)
                        )
                    }
                    // 绘制百分比标签和连接线
                    if (sweepAngle > 5f) {
                        val middleAngleRadians =
                            Math.toRadians((startAngle + sweepAngle / 2).toDouble())
                        val labelRadius = radius * 0.7f
                        val text = "%.1f%%".format(usage.hours / totalHours * 100)
                        val textLayoutResult = textMeasurer.measure(text)
                        // Compute the center of the text to be drawn
                        val textCenterOffset = Offset(
                            x = (labelRadius * cos(middleAngleRadians)).toFloat(),
                            y = (labelRadius * sin(middleAngleRadians)).toFloat()
                        )
                        // The text is drawn from its top-left corner, so we need to adjust the position
                        // to make sure that it's centered on the calculated point
                        val textTopLeft = center + textCenterOffset - Offset(
                            x = (textLayoutResult.size.width / 2).toFloat(),
                            y = (textLayoutResult.size.height / 2).toFloat()
                        )
                        drawText(
                            textLayoutResult = textLayoutResult,
                            topLeft = textTopLeft,
                            color = Color.White
                        )
                    }
                    startAngle += sweepAngle
                }
            }
        }
    }

    if (selectedIndex in appUsages.indices) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .padding(16.dp)
        ) {
            Text(
                text = appUsages[selectedIndex].appName,
                color = MaterialTheme.colorScheme.primary,
                style = MaterialTheme.typography.titleMedium,
                modifier = Modifier.align(Alignment.BottomEnd)
            )
        }
    }
}

@Composable
private fun TreeBarChart(appUsages: List<MainActivity.AppUsage> = emptyList()) {
    val textStyle =
        MaterialTheme.typography.bodyMedium.copy(color = MaterialTheme.colorScheme.onSurface)
    val density = LocalDensity.current

    Box(
        modifier = Modifier
            .fillMaxWidth()
            .height(400.dp)
    ) {
        // Y轴标签
        Canvas(
            modifier = Modifier
                .fillMaxHeight()
                .width(40.dp)
        ) {
            drawIntoCanvas { canvas ->
                val textPaint = android.graphics.Paint().apply {
                    color = Color.DarkGray.toArgb()
                    textSize = 14.sp.toPx()
                    textAlign = android.graphics.Paint.Align.CENTER
                }

                // 旋转画布90度绘制垂直文字
                canvas.withSave {
                    // 调整坐标系并旋转文字
                    // 调整坐标系到左上角并旋转
                    canvas.translate(dx = 0f, dy = 0f)
                    canvas.rotate(-90f)
                    // 计算文字位置（左上角区域）
                    val textX = -size.height + 240.dp.toPx()  // 向下移动更多
                    val textY = 20.dp.toPx()       // 右侧留出更大边距
                    canvas.nativeCanvas.drawText(
                        "使用时长/h",
                        textX,
                        textY,
                        textPaint
                    )
                }
            }
        }

        // 柱状图列表
        LazyRow(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 16.dp)
                .padding(horizontal = 16.dp)
                .align(Alignment.CenterEnd),  // 将图表右对齐留出Y轴标签空间
            horizontalArrangement = Arrangement.spacedBy(8.dp),
            contentPadding = PaddingValues(start = 24.dp, end = 24.dp)
        ) {
            items(appUsages) { appUsage ->
                Column(
                    modifier = Modifier
                        .width(50.dp)  // 调整柱状图宽度以显示更多内容
                        .padding(bottom = 6.dp),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Canvas(
                        modifier = Modifier
                            .weight(1f)
                            .fillMaxWidth()
                    ) {
                        val maxHours =
                            (appUsages.maxOfOrNull { it.hours }?.times(1.2f) ?: 10f).coerceAtLeast(
                                0.1f
                            )
                        val barHeight = (appUsage.hours / maxHours) * size.height
                        val top = size.height - barHeight.coerceAtLeast(1f)

                        drawRect(
                            appUsage.color,
                            topLeft = Offset(0f, top),
                            size = Size(size.width, barHeight)
                        )

                        val textPaint = android.graphics.Paint().apply {
                            color = textStyle.color.toArgb()
                            textSize = textStyle.fontSize.value
                            textAlign = android.graphics.Paint.Align.CENTER
                        }

                        drawIntoCanvas { canvas ->
                            val xCenter = size.width / 2f
                            // 时长显示在柱状图顶部
                            val timeYPos = top - 10.dp.toPx()  // 在柱顶上方10dp
                            // 应用名称显示在底部
                            val nameYPos = size.height + 10.dp.toPx()  // 在画布底部下方10dp

                            // 绘制时长（顶部）
                            canvas.nativeCanvas.drawText(
                                "%.1fh".format(appUsage.hours),
                                xCenter,
                                timeYPos,
                                textPaint.apply {
                                    textSize = 12.sp.toPx()
                                    color = Color.DarkGray.toArgb()
                                }
                            )

                            // 绘制应用名称（底部）
                            canvas.nativeCanvas.drawText(
                                appUsage.appName,
                                xCenter,
                                nameYPos,
                                textPaint.apply {
                                    textSize = 12.sp.toPx()
                                    color = Color.DarkGray.toArgb()
                                }
                            )
                        }
                    }
                }
            }
        }
    }
}


@Preview(showBackground = true, apiLevel = 34)
@Composable
fun ChartPreview() {
    ToolTheme {
        Surface {
            ChartScreen(
                appUsages = listOf(
                    MainActivity.AppUsage("微信", 12.5f, 1),
                    MainActivity.AppUsage("支付宝", 8.2f, 2),
                    MainActivity.AppUsage("抖音", 6.7f, 3),
                    MainActivity.AppUsage("Chrome", 4.1f, 4),
                    MainActivity.AppUsage("YouTube", 3.8f, 5),
                    MainActivity.AppUsage("地图", 2.5f, 6),
                    MainActivity.AppUsage("Gmail", 2.1f, 7),
                    MainActivity.AppUsage("相册", 1.8f, 8),
                    MainActivity.AppUsage("日历", 1.5f, 9)
                ),
                logMessages = listOf(
                    "示例日志1",
                    "示例日志2",
                    "示例日志3"
                ),
                selectedDays = 7,
                selectedAppCount = 10,
                onDaysSelected = {},
                onCountSelected = {}
            )
        }
    }
}


